// export default router;
import Vue from 'vue';
import VueRouter from 'vue-router';
import iView from 'view-design';
import util from '@/libs/util'
import Setting from '@/setting';
import store from '@/store/index';
import { getBtn } from '@/api/permissions'
import { queryLoginUserInfoService } from '@/api/public';
import * as loginUtil from '@/libs/util.login';
import { loginUrl } from '@/constants'
import Cookies from 'js-cookie'
// 路由数据
import routes from './routes';

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter);

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes,
  base: process.env.NODE_ENV === 'development' ? '/' : '/',
  mode: Setting.routerMode
});
/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach((to, from, next) => {
  if (to.query.ucToken) {
    Cookies.set('uc_token', to.query.ucToken)
    // 查询用户信息
    queryLoginUserInfoService({}).then(res => {
      if (res?.retData) {
        localStorage.setItem('userInfo', JSON.stringify(res.retData));
        store.commit('admin/user/SET_USERINFO', res.retData);
      }
    })
  }
  /* 如果没有总的权限列表，就重新获取 */
  if (Cookies.get('uc_token')) {
    if (!sessionStorage.getItem('systemBtnsList')) {
      loginUtil.getAllBtnsList()
    }
    /* 如果没有总的三级菜单，就重新获取三级菜单 */
    if (!sessionStorage.getItem('thirdMenuList')) {
      if (localStorage.getItem('userMenuList')) {
        let menulist = JSON.parse(localStorage.getItem('userMenuList'))
        store.commit('admin/menu/setSider', menulist)
        let thirdMenuList = handleReduceThirdMenuList(menulist)
        sessionStorage.setItem('thirdMenuList', JSON.stringify(thirdMenuList))
      }
    }
    let target = _.find(JSON.parse(sessionStorage.getItem('thirdMenuList')), value => {
      return value.path == to.path
    })
    const data = {
      parentMenuId: target ? target.menuId : ''
    }
    if (Setting.showProgressBar) iView.LoadingBar.start();
    if (to.name && data.parentMenuId) {
      getBtn(data).then(res => {
        if (res.code == 0) {
          let curMenuBtns = []
          res.data && res.data.forEach(value => {
            curMenuBtns.push(value.btnParamNumber)
          })
          store.commit('permissions/systemBtns/SET_CURBTNS_LIST', res.data)
          next()
        }
        if (to.path == '/sourcing/todo-remind') next()
      })
    } else {
      next()
    }
  } else if (loginUtil.getQueryString('m_tk')) {
    next()
  } else {
    window.location.href = loginUrl; // 登录失败，重新跳转登录页
  }
});

router.afterEach(to => {
  if (Setting.showProgressBar) iView.LoadingBar.finish();
  // 多页控制 打开新的页面
  store.dispatch('admin/page/open', to);
  // 更改标题
  util.title({
    title: to.meta.title
  });
  // 返回页面顶端
  window.scrollTo(0, 0);
});

let handleReduceThirdMenuList = (menulist) => {
  return menulist.reduce((value, item) => {
    item.children.forEach(elem => {
      if (elem.children) {
        value.push(...elem.children)
      }
    })
    return value
  }, [])
}

export default router;
